package cn.geminis.auth.controller;

import cn.geminis.auth.model.UserPassword;
import cn.geminis.auth.model.repository.UserPasswordRepository;
import cn.geminis.auth.vo.LoginUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @author puddi
 */
@RestController
@RequestMapping("password")
@RequiredArgsConstructor
public class UserPasswordController {

    private final UserPasswordRepository repository;
    private final PasswordEncoder passwordEncoder;

    @GetMapping
    public LoginUser findOne(String id) {
        var user = this.repository.findById(id).get();

        return LoginUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .build();
    }

    @PostMapping
    public void changePassword(@RequestBody LoginUser user) {
        var dbUser = this.repository.findById(user.getId())
                .orElse(
                        UserPassword.builder()
                                .id(user.getId())
                                .build()
                );

        dbUser.setUsername(user.getUsername());
        dbUser.setPassword3(dbUser.getPassword2());
        dbUser.setPassword2(dbUser.getPassword());
        dbUser.setPassword(passwordEncoder.encode(user.getPassword()));

        this.repository.save(dbUser);
    }

}
